import React, { useState, useEffect, useRef } from 'react';
import styles from './UserCenter.module.css';
import authManager from '../../utils/auth';

interface UserProfile {
  id: number;
  username: string;
  email: string;
  phone: string;
  role: string;
  avatar: string | null;
  createdAt: string;
  lastLogin: string | null;
}

interface Activity {
  id: number;
  action: string;
  description: string;
  timestamp: string;
  ip: string;
}

const UserCenter: React.FC = () => {
  const [activeTab, setActiveTab] = useState<'profile' | 'security' | 'activity'>('profile');
  const [userProfile, setUserProfile] = useState<UserProfile | null>(null);
  const [activities, setActivities] = useState<Activity[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [uploading, setUploading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // 个人信息表单
  const [profileForm, setProfileForm] = useState({
    email: '',
    phone: ''
  });

  // 密码修改表单
  const [passwordForm, setPasswordForm] = useState({
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  });

  const API_BASE = 'http://localhost:3001/api';

  // 获取认证头
  const getAuthHeaders = async () => {
    const headers = await authManager.getAuthHeaders();
    return {
      ...headers,
      'Content-Type': 'application/json'
    };
  };

  // 加载用户数据
  useEffect(() => {
    const loadUserData = async () => {
      try {
        setLoading(true);
        const headers = await getAuthHeaders();
        const [profileResponse, activityResponse] = await Promise.all([
          fetch(`${API_BASE}/user/profile`, { headers }),
          fetch(`${API_BASE}/user/activity`, { headers })
        ]);

        if (profileResponse.ok) {
          const profileData = await profileResponse.json();
          setUserProfile(profileData);
          setProfileForm({
            email: profileData.email || '',
            phone: profileData.phone || ''
          });
        }

        if (activityResponse.ok) {
          const activityData = await activityResponse.json();
          setActivities(activityData);
        }
      } catch (error) {
        console.error('加载用户数据失败:', error);
      } finally {
        setLoading(false);
      }
    };

    loadUserData();
  }, []);

  // 处理头像点击
  const handleAvatarClick = () => {
    fileInputRef.current?.click();
  };

  // 处理文件选择
  const handleFileSelect = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      alert('请选择图片文件');
      return;
    }

    // 验证文件大小
    if (file.size > 2 * 1024 * 1024) {
      alert('图片大小不能超过2MB');
      return;
    }

    await uploadAvatar(file);
  };

  // 上传头像
  const uploadAvatar = async (file: File) => {
    setUploading(true);

    try {
      const formData = new FormData();
      formData.append('avatar', file);

      const authHeaders = await authManager.getAuthHeaders();
      const response = await fetch(`${API_BASE}/user/avatar`, {
        method: 'POST',
        headers: authHeaders,
        body: formData
      });

      const responseText = await response.text();

      if (response.ok) {
        const result = JSON.parse(responseText);
        console.log('上传成功:', result);

        // 更新用户信息中的头像URL
        if (userProfile) {
          const updatedUser = {
            ...userProfile,
            avatar: result.avatar
          };
          setUserProfile(updatedUser);
        }
        alert('头像上传成功！');
      } else {
        const errorData = JSON.parse(responseText);
        throw new Error(errorData.error || '上传失败');
      }
    } catch (error) {
      console.error('上传头像失败:', error);
      if (error instanceof Error) {
        alert(`上传失败: ${error.message}`);
      } else {
        alert('上传失败，请重试');
      }
    } finally {
      setUploading(false);
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    }
  };

  // 删除头像
  const handleDeleteAvatar = async () => {
    if (!window.confirm('确定要删除头像吗？')) return;

    try {
      const headers = await getAuthHeaders();
      const response = await fetch(`${API_BASE}/user/avatar`, {
        method: 'DELETE',
        headers
      });

      if (response.ok) {
        // 更新用户信息，移除头像
        if (userProfile) {
          setUserProfile({
            ...userProfile,
            avatar: null
          });
        }
        alert('头像删除成功！');
      } else {
        const errorData = await response.json();
        throw new Error(errorData.error || '删除失败');
      }
    } catch (error) {
      console.error('删除头像失败:', error);
      if (error instanceof Error) {
        alert(`删除失败: ${error.message}`);
      } else {
        alert('删除失败，请重试');
      }
    }
  };

  // 更新个人信息
  const handleUpdateProfile = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);

    try {
      const headers = await getAuthHeaders();
      const response = await fetch(`${API_BASE}/user/profile`, {
        method: 'PUT',
        headers,
        body: JSON.stringify({
          email: profileForm.email,
          phone: profileForm.phone
        })
      });

      if (response.ok) {
        const updatedUser = await response.json();
        setUserProfile(updatedUser);
        alert('个人信息更新成功！');
      } else {
        const errorData = await response.json();
        throw new Error(errorData.error || '更新失败');
      }
    } catch (error) {
      console.error('更新个人信息失败:', error);
      if (error instanceof Error) {
        alert(`更新失败: ${error.message}`);
      } else {
        alert('更新失败，请重试');
      }
    } finally {
      setSaving(false);
    }
  };

  // 修改密码
  const handleChangePassword = async (e: React.FormEvent) => {
    e.preventDefault();

    if (passwordForm.newPassword !== passwordForm.confirmPassword) {
      alert('新密码和确认密码不一致');
      return;
    }

    if (passwordForm.newPassword.length < 6) {
      alert('新密码长度至少6位');
      return;
    }

    setSaving(true);

    try {
      const headers = await getAuthHeaders();
      const response = await fetch(`${API_BASE}/user/password`, {
        method: 'PUT',
        headers,
        body: JSON.stringify({
          currentPassword: passwordForm.currentPassword,
          newPassword: passwordForm.newPassword
        })
      });

      if (response.ok) {
        alert('密码修改成功！');
        setPasswordForm({
          currentPassword: '',
          newPassword: '',
          confirmPassword: ''
        });
      } else {
        const errorData = await response.json();
        throw new Error(errorData.error || '密码修改失败');
      }
    } catch (error) {
      console.error('修改密码失败:', error);
      if (error instanceof Error) {
        alert(`密码修改失败: ${error.message}`);
      } else {
        alert('密码修改失败，请重试');
      }
    } finally {
      setSaving(false);
    }
  };

  // 格式化时间
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleString('zh-CN');
  };

  if (loading) {
    return (
      <div className={styles.userCenterLoading}>
        <div className={styles.loadingSpinner}>加载中...</div>
      </div>
    );
  }

  return (
    <div className={styles.userCenter}>
      <div className={styles.userCenterHeader}>
        <h1>用户中心</h1>
        <p>管理您的账户信息和安全设置</p>
      </div>

      <div className={styles.userCenterContent}>
        {/* 侧边栏导航 */}
        <div className={styles.userSidebar}>
          <button
            className={`${styles.sidebarItem} ${activeTab === 'profile' ? styles.sidebarItemActive : ''}`}
            onClick={() => setActiveTab('profile')}
          >
            📝 个人信息
          </button>
          <button
            className={`${styles.sidebarItem} ${activeTab === 'security' ? styles.sidebarItemActive : ''}`}
            onClick={() => setActiveTab('security')}
          >
            🔒 安全设置
          </button>
          <button
            className={`${styles.sidebarItem} ${activeTab === 'activity' ? styles.sidebarItemActive : ''}`}
            onClick={() => setActiveTab('activity')}
          >
            📊 活动记录
          </button>
        </div>

        {/* 主要内容区域 */}
        <div className={styles.userMain}>
          {/* 个人信息标签页 */}
          {activeTab === 'profile' && (
            <div className={styles.tabContent}>
              <h2>个人信息</h2>
              <div className={styles.profileCard}>
                <div className={styles.profileHeader}>
                  <div className={styles.avatarSection}>
                    <div
                      className={`${styles.avatar} ${userProfile?.avatar ? styles.avatarHasAvatar : ''}`}
                      onClick={handleAvatarClick}
                      style={{
                        backgroundImage: userProfile?.avatar
                          ? `url(http://localhost:3001${userProfile.avatar})`
                          : undefined,
                        cursor: 'pointer'
                      }}
                    >
                      {!userProfile?.avatar && (userProfile?.username?.charAt(0).toUpperCase() || 'U')}
                    </div>
                    <div className={styles.avatarActions}>
                      <button
                        className={`${styles.avatarBtn} ${styles.changeBtn}`}
                        onClick={handleAvatarClick}
                        disabled={uploading}
                      >
                        {uploading ? '上传中...' : '更换头像'}
                      </button>
                      {userProfile?.avatar && (
                        <button
                          className={`${styles.avatarBtn} ${styles.deleteBtn}`}
                          onClick={handleDeleteAvatar}
                        >
                          删除头像
                        </button>
                      )}
                    </div>
                    <input
                      type="file"
                      ref={fileInputRef}
                      onChange={handleFileSelect}
                      accept="image/*"
                      style={{ display: 'none' }}
                    />
                  </div>
                  <div className={styles.profileInfo}>
                    <h3>{userProfile?.username}</h3>
                    <p className={styles.userRole}>{userProfile?.role}</p>
                    <p className={styles.joinDate}>
                      注册时间: {userProfile?.createdAt ? formatDate(userProfile.createdAt) : '未知'}
                    </p>
                  </div>
                </div>

                <form onSubmit={handleUpdateProfile} className={styles.profileForm}>
                  <div className={styles.formGroup}>
                    <label>用户名</label>
                    <input
                      type="text"
                      value={userProfile?.username || ''}
                      disabled
                      className={styles.disabledInput}
                    />
                    <small>用户名不可修改</small>
                  </div>

                  <div className={styles.formGroup}>
                    <label>邮箱地址</label>
                    <input
                      type="email"
                      value={profileForm.email}
                      onChange={(e) => setProfileForm({ ...profileForm, email: e.target.value })}
                      placeholder="请输入邮箱地址"
                    />
                  </div>

                  <div className={styles.formGroup}>
                    <label>手机号码</label>
                    <input
                      type="tel"
                      value={profileForm.phone}
                      onChange={(e) => setProfileForm({ ...profileForm, phone: e.target.value })}
                      placeholder="请输入手机号码"
                    />
                  </div>

                  <div className={styles.formGroup}>
                    <label>用户角色</label>
                    <input
                      type="text"
                      value={userProfile?.role || ''}
                      disabled
                      className={styles.disabledInput}
                    />
                  </div>

                  <button type="submit" disabled={saving} className={styles.saveBtn}>
                    {saving ? '保存中...' : '保存更改'}
                  </button>
                </form>
              </div>
            </div>
          )}

          {/* 安全设置标签页 */}
          {activeTab === 'security' && (
            <div className={styles.tabContent}>
              <h2>安全设置</h2>
              <div className={styles.securityCard}>
                <form onSubmit={handleChangePassword} className={styles.securityForm}>
                  <div className={styles.formGroup}>
                    <label>当前密码</label>
                    <input
                      type="password"
                      value={passwordForm.currentPassword}
                      onChange={(e) => setPasswordForm({ ...passwordForm, currentPassword: e.target.value })}
                      placeholder="请输入当前密码"
                      required
                    />
                  </div>

                  <div className={styles.formGroup}>
                    <label>新密码</label>
                    <input
                      type="password"
                      value={passwordForm.newPassword}
                      onChange={(e) => setPasswordForm({ ...passwordForm, newPassword: e.target.value })}
                      placeholder="请输入新密码（至少6位）"
                      minLength={6}
                      required
                    />
                  </div>

                  <div className={styles.formGroup}>
                    <label>确认新密码</label>
                    <input
                      type="password"
                      value={passwordForm.confirmPassword}
                      onChange={(e) => setPasswordForm({ ...passwordForm, confirmPassword: e.target.value })}
                      placeholder="请再次输入新密码"
                      minLength={6}
                      required
                    />
                  </div>

                  <button type="submit" disabled={saving} className={styles.saveBtn}>
                    {saving ? '修改中...' : '修改密码'}
                  </button>
                </form>

                <div className={styles.securityTips}>
                  <h4>安全提示：</h4>
                  <ul>
                    <li>密码长度至少6位</li>
                    <li>建议使用字母、数字和特殊符号组合</li>
                    <li>定期更换密码以提高安全性</li>
                    <li>不要使用与其他网站相同的密码</li>
                  </ul>
                </div>
              </div>
            </div>
          )}

          {/* 活动记录标签页 */}
          {activeTab === 'activity' && (
            <div className={styles.tabContent}>
              <h2>活动记录</h2>
              <div className={styles.activityCard}>
                <div className={styles.activityList}>
                  {activities.map(activity => (
                    <div key={activity.id} className={styles.activityItem}>
                      <div className={styles.activityIcon}>
                        {activity.action === 'login' && '🔐'}
                        {activity.action === 'update_profile' && '✏️'}
                        {activity.action === 'view_students' && '👨‍🎓'}
                        {activity.action === 'create_teacher' && '👨‍🏫'}
                      </div>
                      <div className={styles.activityContent}>
                        <div className={styles.activityDescription}>
                          {activity.description}
                        </div>
                        <div className={styles.activityMeta}>
                          <span className={styles.activityTime}>
                            {formatDate(activity.timestamp)}
                          </span>
                          <span className={styles.activityIp}>
                            IP: {activity.ip}
                          </span>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default UserCenter;